import 'package:awak/common/db/db_helper.dart';
import 'package:awak/common/models/review.dart';

class ReviewRepository {
  // 获取所有评论
  Future<List<Review>> getAllReviews() async {
    final db = await DBHelper.database;
    final res = await db.query('review', orderBy: 'createdAt DESC');
    return res.map((e) => Review.fromMap(e)).toList();
  }

  // 根据内容ID获取评论
  Future<List<Review>> getReviewsByContentId(int contentId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'review',
      where: 'contentId = ?',
      whereArgs: [contentId],
      orderBy: 'createdAt DESC',
    );
    return res.map((e) => Review.fromMap(e)).toList();
  }

  // 根据用户ID获取评论
  Future<List<Review>> getReviewsByUserId(int userId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'review',
      where: 'userId = ?',
      whereArgs: [userId],
      orderBy: 'createdAt DESC',
    );
    return res.map((e) => Review.fromMap(e)).toList();
  }

  // 添加评论
  Future<int> addReview(Review review) async {
    final db = await DBHelper.database;
    return await db.insert('review', review.toMap());
  }

  // 更新评论
  Future<int> updateReview(Review review) async {
    final db = await DBHelper.database;
    return await db.update(
      'review',
      review.toMap(),
      where: 'id = ?',
      whereArgs: [review.id],
    );
  }

  // 删除评论
  Future<int> deleteReview(int id) async {
    final db = await DBHelper.database;
    return await db.delete(
      'review',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  // 获取内容的评论数量
  Future<int> getReviewCountByContentId(int contentId) async {
    final db = await DBHelper.database;
    final res = await db.rawQuery(
      'SELECT COUNT(*) as count FROM review WHERE contentId = ?',
      [contentId],
    );
    return res.first['count'] as int;
  }
}
